from flask import Flask
from flask_admin.contrib.sqla import ModelView

from .extensions import *

from config import import_config
from .form.user import ExtendedRegisterForm, ExtendedLoginForm
from .models import User, Role, Article, ArticleView, OutlineView, Outline, CourseView, Course
from .models.user import UserView
from .views import all_bp


def creat_app(mode='production'):
    '''
    核心模块的初始化
    :return: 无
    '''
    app = Flask(__name__)
    if mode != 'production':
        app.env = mode
    config = import_config(app.env)
    app.config.from_object(config)  # 加载配置模块

    # Register components
    # configure_logging(app)
    register_extensions(app)
    register_blueprint(app)

    return app


def register_extensions(app):
    '''
    注册外部插件
    :param app:
    :return:
    '''
    db.init_app(app)
    # user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security._state = security.init_app(app, user_datastore, confirm_register_form=ExtendedRegisterForm,
                                        login_form=ExtendedLoginForm)

    mail.init_app(app)

    # flask-admin configs
    admin.init_app(app)

    admin.add_view(ArticleView(Article, db.session, name='文章管理', category='内容'))
    admin.add_view(OutlineView(Outline, db.session, name='大纲管理', category='内容'))
    admin.add_view(CourseView(Course, db.session, name='课程管理', category='内容'))

    admin.add_view(UserView(User, db.session, name='用户管理', category="用户"))
    admin.add_view(ModelView(Role, db.session, name='角色管理', category="用户"))


def register_blueprint(app):
    '''
    从蓝图列表注册蓝图
    :param app:
    :return:
    '''
    for bp in all_bp:
        app.register_blueprint(bp)